import serial

# 映射寄存器编号到名称（你提供的编码）
reg_map = {
    0: 'ACC',
    1: 'BR',
    2: 'MR',
    3: 'AX',
    4: 'BX',
    5: 'CX',
    6: 'DX',
    7: 'SP'
}

def read_registers_from_uart(port='COM6', baudrate=9600):
    try:
        ser = serial.Serial(port, baudrate, timeout=1)
        print(f"✅ 打开串口 {port}，开始监听数据...\n")
    except Exception as e:
        print(f"❌ 串口打开失败: {e}")
        return

    try:
        while True:
            if ser.in_waiting >= 3:
                # 读取一组三字节
                reg_id = ser.read(1)[0]
                high = ser.read(1)[0]
                low = ser.read(1)[0]
                value = (high << 8) | low

                reg_name = reg_map.get(reg_id, f"R{reg_id}")
                print(f"{reg_name}:{value:04X}")
    except KeyboardInterrupt:
        print("\n🛑 退出")
        ser.close()

if __name__ == '__main__':
    read_registers_from_uart()
